import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Spin, message} from 'antd';
import {hasPermissions, getPrintPageUrl} from './utils';
import {PERMISSION} from './constants';
import {PAGE} from '../constants';
import routes from './routes';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
import CommonDetail from './CommonDetail';
import {exportPi} from './api';
import {exportDownload} from '../utils';
export class Detail extends React.PureComponent {
    state = {
        loading: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleAbandonClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    handleSubmitClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    
    handleInvoiceClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickInvoice().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    
    handleReSettleClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickReSettle().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    
    handleFinanaceClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickFinance().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    onPrint = e => {
        e.stopPropagation();
        window.open(getPrintPageUrl(this.props.id, this.props.currentUserName));
    }
    onExportPi = e => {
        e.stopPropagation();
        exportPi(this.props.id)
            .then(res => {
                this.setState({loading: false});
                exportDownload(res.data);
            });
    }
    onClickApproveBtn = () => {
        if(!this.props.detail.isApprove)
            return message.warn(this.props.intl.formatMessage({
                id: 'detailPanel.message.isAllowApprove',
                defaultMessage: '当前登录人员，不在审核序列中'
            }));
        this.props.history.push(routes.moreApprove.format(this.props.id));
    }
    render() {
        const {options = []} = this.props.detail;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(options, PERMISSION.update))
            operations.push(
                <Button key="update" href={`#${routes.update.format(this.props.id)}`} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.update',
                        defaultMessage: '编辑'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(options, PERMISSION.submit))
            operations.push(
                <WrappedPopconfirm
                    id="submit"
                    key="submit"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleSubmitClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.submit',
                            defaultMessage: '提交'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(options, PERMISSION.approve))
            operations.push(
                <Button key="approve" href={`#${routes.approve.format(this.props.id)}`} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.approve',
                        defaultMessage: '审核'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.invoice) && hasPermissions(options, PERMISSION.invoice))
            operations.push(
                <WrappedPopconfirm
                    id="invoice"
                    key="invoice"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleInvoiceClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.invoice',
                            defaultMessage: '开票通知'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.reSettlement) && hasPermissions(options, PERMISSION.reSettlement))
            operations.push(
                <WrappedPopconfirm
                    id="reSettlement"
                    key="reSettlement"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleReSettleClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.reSettlement',
                            defaultMessage: '反结算'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.finance) && hasPermissions(options, PERMISSION.finance))
            operations.push(
                <WrappedPopconfirm
                    id="finance"
                    key="finance"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleFinanaceClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.finance',
                            defaultMessage: '上报财务'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleAbandonClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.abandon',
                            defaultMessage: '作废'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );

        if(hasPermissions(this.props.permissions, PERMISSION.export) && hasPermissions(options, PERMISSION.export))
            operations.push(
                <Button onClick={this.onPrint} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.export',
                        defaultMessage: '导出'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.exportPi) && hasPermissions(options, PERMISSION.exportPi))
            operations.push(
                <Button onClick={this.onExportPi} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.exportPi',
                        defaultMessage: '导出PI'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.upPi) && hasPermissions(options, PERMISSION.upPi))
            operations.push(
                <Button key="upPi" href={`#${routes.upPi.format(this.props.id)}`} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.upPi',
                        defaultMessage: '上传PI'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.moreApprove) && hasPermissions(options, PERMISSION.moreApprove))
            operations.push(
                <Button key="moreApprove" onClick={this.onClickApproveBtn} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.moreApprove',
                        defaultMessage: '审核'
                    })}
                </Button>
            );
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <CommonDetail
                        detail={this.props.detail}
                        showBrand={this.props.showBrand}
                        operations={operations}
                        isDealerUser={this.props.isDealerUser}
                        isMoneyVisible={this.props.isMoneyVisible}
                        isDetail={true} />
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" disabled={this.props.loading} onClick={this.props.onCancel}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.retrun',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </div>
        );
    }
}
Detail.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    isDealerUser: PropTypes.bool.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickFinance: PropTypes.func.isRequired,
    onClickInvoice: PropTypes.func.isRequired,
    onClickReSettle: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    currentUserName: PropTypes.string,
    history: PropTypes.object,
    intl: PropTypes.object,
    isMoneyVisible: PropTypes.bool,
    showBrand: PropTypes.bool
};
import {connect} from 'react-redux';
import {
    getDetail,
    clearData,
    tableSearch,
    onClickAbandonForDetail,
    onClickSubmitForDetail,
    onClickInvoiceForDetail,
    onClickReSettleForDetail,
    onClickFinanceForDetail,
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    currentUserName: state.getIn(['page', 'domainData', 'initData', 'currentUserName']),
    detail: getDetailData(state),
    showBrand: state.getIn(['page', 'domainData', 'brands', 'data']).size > 1,
    permissions: getPermissions(state),
    isMoneyVisible: state.getIn((['page', 'domainData', 'initData', 'isMoneyVisible'])),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onClickAbandon: () =>
        dispatch(onClickAbandonForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onClickSubmit: () =>
        dispatch(onClickSubmitForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onClickInvoice: () =>
        dispatch(onClickInvoiceForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onClickReSettle: () =>
        dispatch(onClickReSettleForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onClickFinance: () =>
        dispatch(onClickFinanceForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Detail));
